package com.alkaid.user.service.impl;

import com.alkaid.commons.core.CacheKeyDefinition;
import com.alkaid.commons.msg.MsgDefinition;
import com.alkaid.commons.entity.User;
import com.alkaid.commons.ex.SmsSendErrorException;
import com.alkaid.commons.ex.UserNotFoundException;
import com.alkaid.user.mapper.UserMapper;
import com.alkaid.user.service.SmsService;
import com.alkaid.user.utils.HttpUtils;
import com.alkaid.user.utils.RedisUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author Kylin
 * 发送验证码实现类
 */
@Service
public class SmsServiceImpl implements SmsService {


    private UserMapper userMapper;

    private RedisUtils redisUtils;

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Autowired
    public void setRedisUtils(RedisUtils redisUtils) {
        this.redisUtils = redisUtils;
    }

    @Override
    public void sendSmsCode(String mobile, String type) throws UserNotFoundException, SmsSendErrorException {
        // 注册请求发送验证码
        String typeReg = "reg";
        // 是否是注册发送验证码请求
        if (!typeReg.equals(type)) {
            // 从数据库查询
            User user = userMapper.findUserByUsername(mobile);
            if (user == null) {
                // 用户尚未注册
                throw new UserNotFoundException(MsgDefinition.USER_NOT_REG);
            }
        }
        // 生成6位随机验证码
        String smsCode = creatSmsCode();
        System.out.println("[验证码：" + smsCode + "]");
        // 缓存有效期 - 5分钟
        int expireTime = 300;
        if (!redisUtils.save2Redis(CacheKeyDefinition.SMS_KEY_MAP.get(type) + mobile, smsCode, expireTime)) {
            return;
        }

        String host = "https://smssend.shumaidata.com";
        String path = "/sms/send";
        String method = "POST";
        // 购买的AppCode
        String appcode = "df84423cb8c8463f82b60c7633d411e6";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        // 手机号
        querys.put("receive", mobile);
        // 验证码
        querys.put("tag", smsCode);
        // 模板ID 默认-M09DD535F4
        querys.put("templateId", "M09DD535F4");
        Map<String, String> bodys = new HashMap<String, String>();

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
            System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
            throw new SmsSendErrorException(MsgDefinition.SMS_SEND_ERROR);
        }
    }

    /**
     * 生成6位随机验证码
     *
     * @return 6位随机验证码
     */
    private String creatSmsCode() {
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        // 验证码长度
        int smsLength = 6;
        for (int i = 0; i < smsLength; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }
}
